package org.dynamo.database.reverse.config.strings.internal;
/*******************************************************************************
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Jean Neveux - initial API and implementation
 *******************************************************************************/
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.dynamo.database.reverse.emf.metadata.Table;

public class StringDbsUtils {

	private static final String PLURIAL_S = "s";
	private static final String CHAR_Y_TO_IES = "ies";
	private static final char CHAR_Y_PLURIAL = 'y';
	private static final String FKC = "fkc";
	private static final String CAPITAL_SEP = "_";
	
	public static String formatTableName(final String value)
	{
		String []nameParts = value.split(CAPITAL_SEP);
		StringBuilder sb = new StringBuilder();
		if(nameParts.length > 0) {
			for(int i=0;i<nameParts.length;i++)
				sb.append(StringUtils.capitalize(nameParts[i]));
		} else {
			sb.append(StringUtils.capitalize(value));
		}
		return sb.toString();
	}
	
	public static String formatColumnName(final String value)
	{
		String []nameParts = value.split(CAPITAL_SEP);
		StringBuilder sb = new StringBuilder();
		if(nameParts.length > 0) {
			for(int i=0;i<nameParts.length;i++) {
				if(i==0)
					sb.append(nameParts[i]);
				else
					sb.append(StringUtils.capitalize(nameParts[i]));
			}
		} else {
			sb.append(StringUtils.capitalize(value));
		}
		return sb.toString();
	}
	
	public static String formatForeignKey(final String value, final Map<String, Table> containedTable)
	{
		String []nameParts = value.split(CAPITAL_SEP);
		StringBuilder sb = new StringBuilder();
		String lastTableName =  "";
		if(nameParts.length > 0) {
			for(int i=0;i<nameParts.length;i++) {
				if(!nameParts[i].equalsIgnoreCase(FKC))
					sb.append(StringUtils.capitalize(nameParts[i]));
				
				if(containedTable.containsKey(sb.toString()))
				{
					sb = new StringBuilder();
				} else {
					lastTableName = sb.toString();
				}
			}
		} else {
			sb.append(StringUtils.capitalize(value));
		}
		String retName = lastTableName == "" ? sb.toString() : lastTableName;
		
		return StringUtils.uncapitalize(retName);
	}
	
	public static String formatForeignKey(final String value, boolean isMany)
	{
		String retName = formatTableName(value);
		retName = StringUtils.uncapitalize(retName);
		if(isMany)
		{
			if(retName.lastIndexOf(CHAR_Y_PLURIAL) == (retName.length()-1))
			{
				retName = retName.substring(0, retName.length()-1)+CHAR_Y_TO_IES;
			} else {
				retName = retName + PLURIAL_S;
			}
		}
		return retName;
	}
}
